//
//  DDPayViewController.m
//  DingDongZP
//
//  Created by 杨政涛 on 16/10/13.
//  Copyright © 2016年 51ledian.com. All rights reserved.
//

#import "DDPayViewController.h"
#import "DDPayHeaderView.h"
#import "DDPayTableViewCell.h"
#import "DDPayStyleModel.h"
#import "DDPayResultViewController.h"
#import "DDChargeMoneyStyleCell.h"

#import "DDMoneybagHomepageService.h"

#import "DDRechargeTypeModel.h"
#import "DDWeiXinPrePayModel.h"

#import "WXApi.h"


@interface DDPayViewController ()

@property(nonatomic,strong)DDPayHeaderView *headView;

@property(nonatomic,strong)NSArray *listArr;

@property(nonatomic,strong)NSIndexPath *recode;

@property(nonatomic,strong)DDMoneybagHomepageService *moneybagHomepageService;

@property(nonatomic,strong)NSArray *listCout;  // 有多少个充值选项
@property(nonatomic,strong)NSArray *chargeMoneyLogo;  // 充值种类的logo


@property(nonatomic,strong)DDRechargeTypeModel *rechargeType;

@property(nonatomic,strong)DDWeiXinPrePayModel *weiXinPrePayModel;


@property(nonatomic,strong)NSIndexPath *recodeChargeMoney; //选择的是第几个充值类型

@end

@implementation DDPayViewController

{
    
    UIButton *payButton;  // 支付按钮  全局变量
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.rdv_tabBarController setTabBarHidden:true animated:true];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"充值";
    
    self.chargeMoneyLogo = @[@"pay1",@"pay2",@"pay3",@"pay4",@"pay5",@"pay6",@"pay6",@"pay6",@"pay6",@"pay6"];
    
    
//    self.listArr = @[@{@"leftImage":@"支付宝logo.png",@"payStyle":@"支付宝支付",@"subtitle":@"推荐有支付宝账号的用户使用"},@{@"leftImage":@"微信logo.png",@"payStyle":@"微信支付",@"subtitle":@"推荐安装微信5.0及以上版本使用"}];

    /**
     *  隐藏支付宝支付
     */
    self.listArr = @[@{@"leftImage":@"微信logo.png",@"payStyle":@"微信支付",@"subtitle":@"推荐安装微信5.0及以上版本使用"}];

    self.moneybagHomepageService = [[DDMoneybagHomepageService alloc]init];

    [self setupData];
    
    [self configureTableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultForWeiXing:) name:NOTI_PayResult_WeiXing object:nil];
}

- (void)configureTableView
{
    WEAKSELF
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
      
        make.top.mas_equalTo(weakSelf.view);
        make.left.mas_equalTo(weakSelf.view);
        make.right.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(weakSelf.view);
    }];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.headView = [[DDPayHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,89)];
    
    self.tableView.tableHeaderView = self.headView;
    
}

#pragma mark  UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
      
        return 84;
    }else{
     
        return 62;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    if (section == 0) {
        
        return self.listCout.count;
    }
    
    return self.listArr.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (indexPath.section == 0) {
        
        
        DDChargeMoneyStyleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chargecell"];
        if (cell == nil) {
            
            cell = [[DDChargeMoneyStyleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"chargecell"];
        }
        
        NSDictionary *dict = self.listCout[indexPath.row];
        self.rechargeType = [DDRechargeTypeModel yy_modelWithJSON:dict];
        self.rechargeType.leftImage = self.chargeMoneyLogo[indexPath.row];
        cell.dataModel = self.rechargeType;
        
        return cell;
    }else{
    
    DDPayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"payStyle"];
    if (cell == nil) {
        
        cell = [[DDPayTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"payStyle"];
    }
    
    NSDictionary *dict = self.listArr[indexPath.row];
    DDPayStyleModel *model = [DDPayStyleModel yy_modelWithDictionary:dict];
    cell.dataModel = model;
    
    return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (section == 0) {
        
        return 14;
    }else{
    
         return 35;
    }
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (section == 0) {
        
        return nil;
    }else{
    
    UIView *sectionHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, CGRectGetWidth(sectionHeaderView.bounds)-15, CGRectGetHeight(sectionHeaderView.bounds)-15)];
    titleLabel.text = @"选择支付方式";
    titleLabel.textColor = COLOR_FONT_LIGHT_GRAY;
    titleLabel.font = [UIFont systemFontOfSize:13];
    [sectionHeaderView addSubview:titleLabel];
    return sectionHeaderView;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    if (section == 0) {
        
        return 1;
    }else{
    
    return 130;
    }
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    if (section == 0) {
        
        return nil;
    }else{
    
    UIView *sectionFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,130)];
    
    payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    payButton.backgroundColor = COLOR_BUTTON_MAIN_RED;
    payButton.layer.masksToBounds = YES;
    payButton.layer.cornerRadius = 5;
    [payButton setTitle:@"充值" forState:UIControlStateNormal];
    [payButton addTarget:self action:@selector(payAction) forControlEvents:UIControlEventTouchUpInside];
    [sectionFooterView addSubview:payButton];
    
    [payButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(sectionFooterView).offset(40);
        make.left.mas_equalTo(sectionFooterView).offset(30);
        make.right.mas_equalTo(sectionFooterView).offset(-30);
        make.height.equalTo(@(45));
    }];
    
    UILabel *remarks = [[UILabel alloc]init];
    remarks.text = @"注：支付成功后，金额会直接充到您的余额中";
    remarks.font = [UIFont systemFontOfSize:13];
    remarks.textColor = COLOR_FONT_LIGHT_GRAY;
    [sectionFooterView addSubview:remarks];
    [remarks mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(payButton.mas_bottom).offset(15);
        make.left.right.mas_equalTo(payButton);
        make.height.equalTo(@(15));
    }];
    
    return sectionFooterView;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    //  选择充值金额
    if (indexPath.section == 0) {
        
        if (self.recodeChargeMoney == indexPath) {
            
            if (self.recodeChargeMoney){
            DDChargeMoneyStyleCell *cell = [self.tableView cellForRowAtIndexPath:self.recodeChargeMoney];
            cell.selectedImage.image = [UIImage imageNamed:@"gou2"];
            
            self.recodeChargeMoney = nil;
        
            }else{
            
            DDChargeMoneyStyleCell *cell = [self.tableView cellForRowAtIndexPath:self.recodeChargeMoney];
            cell.selectedImage.image = [UIImage imageNamed:@"gou1"];
                
            self.recodeChargeMoney = indexPath;
        }
            
        }else{
            DDChargeMoneyStyleCell *cell = [self.tableView cellForRowAtIndexPath:self.recodeChargeMoney];
            cell.selectedImage.image = [UIImage imageNamed:@"gou2"];
            
            DDChargeMoneyStyleCell *cell2 = [self.tableView cellForRowAtIndexPath:indexPath];
            cell2.selectedImage.image = [UIImage imageNamed:@"gou1"];
            
            self.recodeChargeMoney = indexPath;
        }
    }
    
    // 选择支付宝支付还是微信支付
    else{
    if (self.recode == indexPath) {
        
        if (self.recode) {
            
            DDPayTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.recode];
            cell.selectedImage.image = [UIImage imageNamed:@"gou2"];
            
            self.recode = nil;

        }else{
           
            DDPayTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.recode];
            cell.selectedImage.image = [UIImage imageNamed:@"gou1"];

            self.recode = indexPath;
        }
    }else{
        DDPayTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.recode];
        cell.selectedImage.image = [UIImage imageNamed:@"gou2"];

        DDPayTableViewCell *cell2 = [self.tableView cellForRowAtIndexPath:indexPath];
        cell2.selectedImage.image = [UIImage imageNamed:@"gou1"];

        self.recode = indexPath;
    }
    
    }
}


// 网络请求
- (void)setupData
{
    
    WEAKSELF
    [self.moneybagHomepageService queryRechargeTypeSuccessBlock:^(id responseObject) {
        
        
        self.listCout = responseObject[@"data"][@"list"];
        
        [self performSelectorOnMainThread:@selector(backToMainToUpdata) withObject:self waitUntilDone:YES];
        
    } failBlock:^(id responseObject, NSError *error) {
        
        [weakSelf requestFaild];
    }];
}

- (void)backToMainToUpdata
{

    [self.tableView reloadData];
}

// 支付
- (void)payAction
{
   
    WEAKSELF
    if (!self.recodeChargeMoney) {
        
        [weakSelf showLDAlertView:@"请先选择充值金额"];
    }else{
    
        if (!self.recode) {
            
            [weakSelf showLDAlertView:@"请选择支付方式"];
        }else{
            
            switch (self.recode.row) {
   
                case 0:
                {
                    
                 // 防止重复点击
                 payButton.userInteractionEnabled = NO;
                 
                    // 微信支付 先请求后台
                [self prePayForWeiXinToSeverWithid:[NSString stringWithFormat:@"%@",self.listCout[self.recodeChargeMoney.row][@"id"]]];
                }
                    break;
                default:
                    break;
            }
        }
    }
}

/**
 *  后台收到用户支付单接口
 *
 *  @param payArryID    选择支付种类数组的ID
 */
- (void)prePayForWeiXinToSeverWithid:(NSString *)payArryID
{
    [self showLoadingWithText:@"正在跳转..."];
    WEAKSELF
    
    [self.moneybagHomepageService prePayForWeiXinToSeverWithid:payArryID SuccessBlock:^(id responseObject) {
       
    [self hideLoading];
        
    self.weiXinPrePayModel = [DDWeiXinPrePayModel yy_modelWithJSON:responseObject[@"data"]];
        
    [self performSelectorOnMainThread:@selector(backToMainToShowPayPre) withObject:self waitUntilDone:YES];
        
    } failBlock:^(id responseObject, NSError *error) {
        
        [self showErrorWithText:@"支付失败"];
        [weakSelf requestFaild];
    }];
}

- (void)backToMainToShowPayPre
{
    
    if (!([WXApi isWXAppInstalled])){
    
        [[LDShowHUB shareInstance] showErr:@"未安装微信"];
        // 打开可点击
        payButton.userInteractionEnabled = YES;

    }else{
//    调起微信支付
    PayReq* req = [[PayReq alloc]init];
    
    req.openID = @"wx6715d25ff26c2770";
    req.partnerId = @"1342676501";
    req.prepayId = self.weiXinPrePayModel.prepayid;
    req.nonceStr = self.weiXinPrePayModel.noncestr;
    req.timeStamp = self.weiXinPrePayModel.timestamp;
    req.package = self.weiXinPrePayModel.package;
    req.sign = self.weiXinPrePayModel.sign;
    
    [WXApi sendReq:req];
        
    }
}

// 微信支付的结果
-(void)payResultForWeiXing:(NSNotification *)info
{
    
    // 打开可点击
    payButton.userInteractionEnabled = YES;
    
    NSDictionary *dict = (NSDictionary *)info.userInfo;

    NSString *payResult = [NSString stringWithFormat:@"%@",dict[@"payResoult"]];
   
    DDPayResultViewController *payResultpVC = [[DDPayResultViewController alloc]init];

    if ([payResult isEqualToString:@"微信支付成功"]) {
        
        payResultpVC.payResult = @"充值成功";
        [self.navigationController pushViewController:payResultpVC animated:YES];
    }

    if ([payResult isEqualToString:@"微信支付失败"]) {
      
        payResultpVC.payResult = @"充值失败";
        [self.navigationController pushViewController:payResultpVC animated:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    
    [self.rdv_tabBarController setTabBarHidden:false animated:true];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
